<template>
  <div class="app-container">
    <!-- 项目名称 -->
    <h1 style="padding:30px; color:#fff;font-size:30px;">虚拟币量化交易系统</h1>
    <el-row class="controw" v-if="type == 'login'">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <!-- 登录表单 -->
        <el-card v-if="showLogin" class="box-card">
          <el-form
            ref="loginForm"
            key="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            size="medium"
          >
            <div class="title-form-container">
              <h3 class="title-form">欢迎登录</h3>
              <span class="form-line"/>
            </div>

            <el-form-item prop="username">
              <el-input
                ref="username"
                v-model.trim="loginForm.username"
                placeholder="手机号"
                name="username"
                type="text"
                tabindex="1"
                @change="phoneChange($event, 'loginForm')"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                key="loginFormpassword"
                v-model.trim="loginForm.password"
                placeholder="密码"
                name="password"
                show-password
              />
            </el-form-item>
            <el-form-item v-if="showPicUi" prop="graphVerifyCode">
              <el-col :span="16">
                <el-input
                  v-model.trim="loginForm.graphVerifyCode"
                  placeholder="图片验证码"
                  class="verifyCode"
                  @keyup.enter.native="handleLogin"
                />
              </el-col>
              <el-col :span="8">
                <img
                  class="verifyCodeImg"
                  :src="imgUrl"
                  @click="resetImg('loginForm', loginForm.username)"
                />
              </el-col>
            </el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              style="width:100%;"
              size="medium"
              :disabled="loading"
              @click.native.prevent="handleLogin"
              @keyup.enter.native="handleLogin"
            >登录
            </el-button>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <el-row class="controw" v-if="type == 'changePass'">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <!-- 登录表单 -->
        <el-card v-if="showLogin" class="box-card">
          <el-form
            ref="changeForm"
            key="changeForm"
            :model="changeForm"
            :rules="changeRules"
            class="login-form"
            size="medium"
          >
            <div class="title-form-container">
              <h3 class="title-form">找回密码</h3>
              <span class="form-line"/>
            </div>

            <el-form-item prop="username">
              <el-input
                ref="username"
                v-model.trim="changeForm.username"
                placeholder="账号"
                name="username"
                type="text"
                tabindex="1"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                key="loginFormpassword"
                v-model.trim="changeForm.password"
                placeholder="旧密码"
                name="password"
                show-password
              />
            </el-form-item>
            <el-form-item prop="rePassword">
              <el-input
                v-model.trim="changeForm.rePassword"
                placeholder="确认密码"
                name="rePassword"
                show-password
              />
            </el-form-item>

            <div style="text-align:right">
              <el-button type="text" size="mini" @click="cutType('2')"
              >返回登录
              </el-button
              >
            </div>

            <el-button
              :loading="loading"
              type="primary"
              style="width:100%;"
              size="medium"
              :disabled="loading"
              @click.native.prevent="changePass"
              @keyup.enter.native="changePass"
            >找回密码
            </el-button>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {guid, validatePhone} from "@/utils/validate";
  import {
    preLogin,
    register,
    lostPwd,
    sendCaptcha,
    graphVerifyCode,
    changePass
  } from "@/api/user";

  export default {
    name: "Login",
    inject: ["reload"],
    data() {
      const checkPhone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("手机号不能为空"));
        } else {
          const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error("请输入正确的手机号"));
          }
        }
      };

      return {
        id: "",
        // 获取验证码
        regdisabled: false,
        showRole: false,
        enableRoleSelect: false,
        roleList: [],
        time: 5,
        btntxt: "发送验证码",
        // 登录表单
        loginForm: {
          username: "",
          password: "",
          graphVerifyCode: ""
        },
        // 找回密码表单
        changeForm: {
          username: "",
          password: "",
          rePassword: ""
        },
        changeRules: {
          username: [
            {
              required: true,
              validator: checkPhone,
              message: "请输入正确的手机号"
            }
          ],
          password: [
            {required: true, trigger: "blur", message: "请输入新密码"},
            {min: 6, max: 100, message: "长度在6到100个字符", trigger: "blur"}
          ],
          rePassword: [
            {required: true, trigger: "blur", message: "请输入确认密码"},
            {min: 6, max: 100, message: "长度在6到100个字符", trigger: "blur"}
          ]
        },
        loginRules: {
          username: [
            {
              required: true,
              validator: checkPhone,
              message: "请输入正确的手机号"
            }
          ],
          password: [
            {required: true, trigger: "blur", message: "请输入密码"},
            {min: 6, max: 100, message: "长度在6到100个字符", trigger: "blur"}
          ],
          graphVerifyCode: [
            {required: true, trigger: "blur", message: "请输入图片验证码"}
          ]
        },
        // 注册表单
        updateForm: {
          account: "",
          password: "",
          confirmPassword: "",
          imageVerifyCode: ""
        },
        passwordType: "password",
        loading: false,
        showDialog: false,
        redirect: undefined,
        otherQuery: {},
        checked: true,
        showLogin: true,
        showReg: false,
        // 修改表单
        showUpdatePwd: false,
        regForm: {
          account: "",
          name: "",
          verifyCode: "",
          password: "",
          confirmPassword: "",
          epName: "",
          ceoName: "",
          imgNum: ""
        },
        resvalue: null,
        imgUrl: "",
        environment: process.env.VUE_APP_BASE_API,
        showPicUi: false,
        showOld: false,
        type: "login"
      };
    },
    watch: {
      $route: {
        handler: function (route) {
          const query = route.query;
          if (query) {
            this.redirect = query.redirect;
            this.otherQuery = this.getOtherQuery(query);
          }
        },
        immediate: true
      }
    },

    created() {
      this.id = guid();
    },
    methods: {
      phoneChange(val, form) {
        const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
        if (reg.test(val)) {
          this.showPicUi = true;
          this.resetImg(form, val);
        }
      },
      resetImg(form, val) {
        if (form == "loginForm") {
          if (!this[form].username) {
            this.$message.error("请先输入手机号");
            return true;
          }
        } else {
          if (!this[form].account) {
            this.$message.error("请先输入手机号");
            return true;
          }
        }
        graphVerifyCode(val).then(res => {
          this.imgUrl = "data:image/png;base64," + res.data;
        });
      },
      pwChange() {
        this.loading = true;
        const _this = this;
        const data = {
          account: _this.loginForm.username,
          password: _this.loginForm.password
        };
        preLogin(data)
          .then(function (res) {
            const that = this;
            if (res.code === 20000) {
              const resquest = res.data;
              _this.roleList = resquest;
            }
            that.loading = false;
          })
          .catch(_ => {
            this.loading = false;
          });
      },

      // 只能中文
      inputChange(e) {
        const o = e.target;
        o.value = o.value.replace(/[^\u4E00-\u9FA5]/g, ""); // 清除除了中文以外的输入的字符
        this.name = o.value;
      },
      // 切换登录注册
      toggleForm(isLogin, isReg) {
        this.showLogin = isLogin;
        this.showReg = isReg;
        this.clearCode();
      },
      showRegForm() {
        this.resetForm("loginForm");
        this.toggleForm(false, true);
      },
      // 登录
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            this.$store
              .dispatch("user/login", this.loginForm)
              .then(() => {
                const that = this;
                that.$router.push({
                  path: "/",
                  query: that.otherQuery
                });

                that.loading = false;
              })
              .catch(_ => {
                console.log("catch");
                this.resetImg("loginForm", this.loginForm.username);
                this.loading = false;
              });
          } else {
            return false;
          }
        });
      },
      // 找回密码
      changePass() {
        console.log(this.changeForm);
        this.$refs.changeForm.validate(valid => {
          if (valid) {
            this.loading = true;
            console.log(this.changeForm);
            changePass(this.changeForm).then(res => {
              this.$message.success("找回密码成功");
              this.type = "login";
            });
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      getOtherQuery(query) {
        return Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
      },
      sendCode(form) {
        const parmars = {
          phone: form === "loginForm" ? this[form].username : this[form].account
        };
        sendCaptcha(parmars)
          .then(res => {
            if (res.code === 20000) {
              this.time = 60;
              this.timer();
            }
          })
          .catch(_ => {
          });
      },
      showLoginForm() {
        this.showLogin = true;
        this.showReg = false;
        this.showUpdatePwd = false;
      },
      handleUpdate() {
        this.$refs.updateForm.validate(async valid => {
          if (valid) {
            this.updateHandle();
          }
        });
      },
      updateHandle() {
        const parmars = {
          ...this.updateForm
        };
        lostPwd(parmars)
          .then(res => {
            if (res.code === 20000) {
              this.$message.success(res.msg);
              this.showLoginForm();
            }
          })
          .catch(_ => {
          });
      },
      cutType(state) {
        if (state === "1") {
          this.type = "changePass";
        } else {
          this.type = "login";
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #000;
  $blue: #1890ff;
  .app-container {
    min-height: calc(100vh - 50px);
    width: calc(100% - 10px);
    background: $bg url("./bj.jpg") no-repeat center center;
    /*background-size: cover;*/
    /*overflow: hidden;*/
  }

  .controw {
    display: flex;
    min-height: 100%;
    align-items: center;
    justify-content: flex-end;
  }

  .projecttitle {
    position: absolute;
    background: rgba(255, 255, 255, 0.31);
    left: 0;
    top: 50%;
    width: 100%;
    height: 180px;
    margin-top: -90px;
  }

  .title-project {
    display: flex;
    flex-direction: column;
    justify-content: center;
    color: #fff;
    text-align: center;
    font-size: 50px;
    margin: 0;
    padding: 30px;
  }

  .title-project p {
    height: 60px;
    line-height: 60px;
    margin: 0;
    flex: 1;
  }

  .box-card {
    width: 450px;
    margin: 0 auto;
    //position: absolute;
    //top: 50%;
    //left: 85%;
    // transform: translate(-85%, -50%);
  }

  .title-form-container {
    text-align: center;
  }

  .form-line {
    height: 1px;
    width: 30px;
    border-bottom: solid 2px $blue;
    display: block;
    margin: 0 auto;
    margin-bottom: 30px;
  }

  .center {
    text-align: center;
  }

  .margin {
    margin: 10px 0;
  }

  .verifyCode {
    width: "60%";
  }

  .verifyCodeImg {
    margin-top: 5px;
    margin-left: 10px;
    height: 30px;
    width: "60%";
  }
</style>
